package com.kaifamiao.store.system.aspect;


import com.kaifamiao.store.system.annotation.Premission;
import com.kaifamiao.store.system.domain.User;
import com.kaifamiao.store.system.ex.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.List;

@Aspect // 表示这是一个切面类
@Component // 表示这是一个组件
@Slf4j
public class PermissionProxy {

    @Autowired
    private RedisTemplate redisTemplate;

    @Before("@annotation(premission)")
    public void before(JoinPoint joinPoint, Premission premission) throws ServiceException {
        log.info("方法执行前，需要的权限：{}", premission.value());
        String permission = premission.value();
        // 获取用户的 id, 需要 request 中获取
        // 通过 RequestContextHolder 获取 request 上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (ObjectUtils.isEmpty(requestAttributes)) {
            throw new ServiceException("鉴权失败, 请重试");
        }
        User user = (User) requestAttributes.getAttribute("user", 0);
        String userId = user.getId();
        // 获取用户的权限
        List<String> permissions = redisTemplate.opsForList().range("permissions_" + userId, 0, -1);

        if (permissions.contains(permission)) {
            log.info("用户拥有权限，可以执行方法");
            return;
        }
        throw new ServiceException("没有访问权限");
    }

}
